//
//  PartChooseVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/10/24.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "PartChooseVC.h"

@interface PartChooseVC ()
{
    NSInteger num;
    UITextField *_searchTF;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property(nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,strong)NSMutableArray *discrbArr;
@property (nonatomic,assign)NSInteger lastId;
@end

@implementation PartChooseVC
- (AFHTTPSessionManager *)manager{

    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"配件选择";
    self.view.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    //获取通知中心单例对象
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(notice) name:@"cellnotice2" object:nil];
    
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *dele = app.delegate;
    self.userID = dele.userId;
    
    [self initSearchView];
    
    
}
- (void)initSearchView{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, 60)];
    headerView.backgroundColor = [UIColor whiteColor];
    headerView.layer.shadowColor = [UIColor grayColor].CGColor;
    headerView.layer.shadowOffset = CGSizeMake(0, 0);
    headerView.layer.shadowOpacity = 1.0f;
    _searchTF = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, kSCREEN_WIDTH-70, 40)];
    _searchTF.borderStyle = UITextBorderStyleLine;
    _searchTF.layer.borderColor = UIColorFromRGB(0x0093d5).CGColor;
    _searchTF.layer.borderWidth = 2.0;
    _searchTF.placeholder = @"输入物料编码／描述";
    [headerView addSubview:_searchTF];
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView).offset(10);
        make.left.equalTo(_searchTF.mas_right).offset(0);
        make.size.mas_equalTo(CGSizeMake(50, 40));
    }];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 59, kSCREEN_WIDTH, 1)];
    line.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [headerView addSubview:line];
    [self.view addSubview:headerView];
    
}
- (void)initView{
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 124, kSCREEN_WIDTH, kSCREEN_HEIGHT-126) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.rowHeight = 160;
    _tableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];

    //v.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [self.tableview setTableFooterView:v];
        //self.tableview.tableHeaderView = headerView;
    [self.view addSubview:_tableview];
    
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.lastId = 0;
        [self load];
    }];
    
    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        PartMtsModel *model = [_discrbArr lastObject];
        self.lastId = model.ID;
        [self load];
    }];


}
#pragma mark-->tableview

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _discrbArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PartChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        
        cell = [[PartChooseCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    PartMtsModel *model = _discrbArr[indexPath.row];
    [cell fillCellWithModel:model];
    return cell;
}


- (void)searchBtnClick{

    [_nothing removeFromSuperview];
    [self initView];
    [self.tableview.mj_header beginRefreshing];

}
/**
 *  停止刷新
 */
-(void)endRefresh{
    
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
}
- (void)load{
    
    _discrbArr = [[NSMutableArray alloc]init];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_MtPcsSearch parameters:@{kword:_searchTF.text,@"lastId":[NSString stringWithFormat:@"%ld",self.lastId],userid:[NSString stringWithFormat:@"%ld",self.userID]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self endRefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSInteger statue = [dic[@"status"]integerValue];
        
        PDataModel *datamodel = [[PDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        
        for (PartMtsModel *model in datamodel.mtstock) {
            [_discrbArr addObject:model];
        }
        if (_discrbArr.count == 0) {
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 124, kSCREEN_WIDTH, kSCREEN_HEIGHT-124) title:@"没有搜到您要的数据"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }
        [self.tableview reloadData];
            
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"未能连接到服务器。"]){
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            
        }

    }];
}
- (void)NothingRefresh:(UIButton *)sender{
    
    [_nothing removeFromSuperview];
    [self initView];
    [self.tableview.mj_header beginRefreshing];

}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self initView];
    [self.tableview.mj_header beginRefreshing];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self initView];
    [self.tableview.mj_header beginRefreshing];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)notice{
    
    
    
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]removeObserver:@"cellnotice2"];
    
}

- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
